package com.hzit.service.impl;

import cn.hutool.core.util.StrUtil;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hzit.entity.PageResult;
import com.hzit.entity.Student;
import com.hzit.entity.StudentExample;
import com.hzit.mapper.StudentMapper;
import com.hzit.service.IStudentService;
import com.hzit.vo.StudentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements IStudentService {
	@Autowired
	private StudentMapper studentMapper;
	/**
	 * 1. 实现条件查询带分页
	 * @param page
	 * @param pageSize
	 * @param vo
	 * @return
	 */
	@Override
	public PageResult<Student> search(int page, int pageSize, StudentVo vo) {
		//1. 开始分页
		PageHelper.startPage(page,pageSize);
		//2. 开始查询
		//2.1 封装查询条件
		StudentExample example = new StudentExample();                  // 一次查询过程
		StudentExample.Criteria criteria = example.createCriteria();    // 查询条件
		if(vo != null){
			if(StrUtil.isNotBlank(vo.getSname())){
				criteria.andSnameLike("%" + vo.getSname() + "%");       // 相当于： sname like '%xxx%'
			}
			if(StrUtil.isNotBlank(vo.getAddr())){
				criteria.andAddrLike("%" + vo.getAddr() + "%");         // 相当于： addr like '%xxx%'
			}
			if(vo.getCid() != null && vo.getCid() != 0){                     // 相当于：cid = xxx
				criteria.andCidEqualTo(vo.getCid());
			}
		}
		//2.2 根据条件进行查询出结果
		List<Student> students = studentMapper.selectByExample(example);
		//2.3 转换结果为Page对象
		Page<Student> studentPage = (Page<Student>) students;

		return new PageResult<>(studentPage.getResult(),studentPage.getTotal());
	}
}
